import 'package:ball_lion/module/expert/items/plan_item.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/home/comments/comment_input.dart';
import 'package:ball_lion/module/home/post_cell.dart';
import 'package:ball_lion/widgets/asset_item.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/module/home/news_detail_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';
import 'package:ball_lion/widgets/share/share_sheet.dart';
import 'comments/comment_Item.dart';
import 'comments/news_share_append.dart';
import 'news_cell.dart';
import 'news_detail_view.dart';

class NewsDetail extends StatefulWidget {
  const NewsDetail({super.key});

  @override
  State<NewsDetail> createState() => _NewsDetailState();
}

class _NewsDetailState extends State<NewsDetail> {
  final NewsDetailLogic logic =
      Get.put(NewsDetailLogic(), tag: '${Get.arguments}');

  @override
  Widget build(BuildContext context) {
    return GetBuilder<NewsDetailLogic>(
        tag: '${Get.arguments}',
        builder: (logic) {
          return LoadingWidget<bool>(
            isLoading: logic.data == null,
            data: logic.data?.content == null,
            child: () => Scaffold(
              backgroundColor: Colours.greyF2F3F7,
              appBar: Styles.appBar(title: appBarTitle(), actions: [
                GestureDetector(
                  // onTap: () async {
                  //   Utils.onEvent("article_share", params: {
                  //     "article_id": logic.data?.id,
                  //     "channel": logic.id
                  //   });
                  //   final news = logic.data;
                  //   final classId = logic.classId;
                  //   if (news == null) {
                  //     return;
                  //   }
                  //   Get.bottomSheet(
                  //       ShareSheet(
                  //           append:
                  //               NewsShareAppend(news: news, classId: classId)),
                  //       settings: RouteSettings(
                  //           arguments:
                  //               ShareEntity(url: 'tg/articles/${news.id}')));
                  // },
                  child: SizedBox(
                    height: Get.height,
                    child: Image.asset(
                      Utils.getImgPath("news_detail_more.png"),
                      width: 24,
                      height: 24,
                    ).marginOnly(right: 16),
                  ),
                )
              ]),
              body: Column(
                children: [
                  Expanded(
                    child: EasyRefresh.builder(
                      controller: logic.refreshController,
                      scrollController: logic.scrollC,
                      // onRefresh: logic.getRefresh,
                      onLoad: logic.loadMore,
                      header: Styles.refreshHeader(
                          position: IndicatorPosition.locator),
                      footer: Styles.refreshFooter(
                          position: IndicatorPosition.locator),
                      childBuilder: (context, physics) => SliverViewObserver(
                        controller: logic.observer,
                        child: CustomScrollView(
                          physics: physics,
                          controller: logic.scrollC,
                          slivers: [
                            logic.data?.type == 2
                                ? SliverToBoxAdapter(
                                    child: PostCell(
                                    logic.data!,
                                    type: 1,
                                  ))
                                : SliverToBoxAdapter(
                                    child: NewsDetailView(
                                        data: logic.data, id: logic.id)),
                            if (logic.plan?.hasValue ?? false) ...[
                              SliverToBoxAdapter(
                                child: const QsText(
                                  "相关专家方案",
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                ).marginOnly(top: 12, left: 16),
                              ),
                              SliverList.list(
                                  children: logic.plan
                                          ?.map((e) => Block(
                                              cardStyle: const CardStyle(
                                                  margin: EdgeInsets.fromLTRB(
                                                      8, 8, 8, 0),
                                                  padding: EdgeInsets.symmetric(
                                                      horizontal: 12)),
                                              child: PlanItem(
                                                  entity: e,
                                                  eventType:
                                                      "article_plan_view",
                                                  id: logic.id)))
                                          .toList() ??
                                      [])
                            ],
                            if (logic.showRelative) ...[
                              SliverToBoxAdapter(
                                child: const QsText(
                                  "相关资讯",
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                ).marginOnly(left: 16, top: 8, bottom: 8),
                              ),
                              SliverList.list(
                                  children: List.generate(
                                      logic.data!.list!.length,
                                      (index) => NewsItemCell(
                                            logic.data!.list![index],
                                            classId: logic.classId,
                                            inHome: false,
                                            imgStyle: logic
                                                .data!.list![index].imgStyle,
                                            bottomDivider: index !=
                                                logic.data!.list!.length - 1,
                                            afterRoute: () => setState(() {}),
                                            onTap: () => Utils.onEvent(
                                                'article_other_article_view',
                                                params: {
                                                  'article_id': logic
                                                      .data!.list![index].id,
                                                  "channel": logic.id
                                                }),
                                          )))
                            ],
                            // SliverToBoxAdapter(
                            //   child: Container(
                            //       color: Colours.white,
                            //       margin: const EdgeInsets.only(top: 8),
                            //       padding: const EdgeInsets.all(16),
                            //       child: Row(
                            //         children: [
                            //           const QsText("评论",
                            //               fontSize: 16, color: Colours.text),
                            //           if (logic.data?.commentNum.hasValue ??
                            //               false)
                            //             QsText("（${logic.data?.commentNum}）",
                            //                 fontSize: 12,
                            //                 color: Colours.grey66),
                            //           const Spacer(),
                            //           if (logic.comments.hasValue)
                            //             AssetItem(
                            //                 asset: "comment_sort.png",
                            //                 name: logic.commentSort == 1
                            //                     ? "按热度"
                            //                     : "按时间",
                            //                 assetSize: 10,
                            //                 space: 5,
                            //                 direction: AssetDirection.ltr,
                            //                 textStyle: const TextStyle(
                            //                   color: Colours.grey66,
                            //                   fontSize: 13,
                            //                 ),
                            //                 onTap: () {
                            //                   logic.commentSort =
                            //                       logic.commentSort == 1
                            //                           ? 2
                            //                           : 1;
                            //                   logic.getComments();
                            //                 }),
                            //         ],
                            //       )),
                            // ),
                            // if (logic.comments.hasValue) ...[
                            //   SliverList.builder(
                            //       itemCount: logic.comments?.length,
                            //       itemBuilder: (context, index) {
                            //         return Container(
                            //           color: Colours.white,
                            //           padding: const EdgeInsets.symmetric(
                            //               horizontal: 16),
                            //           child: CommentItem(
                            //             newsId: logic.newsId,
                            //             comment: logic.comments![index],
                            //             onReport: (String reason) =>
                            //                 logic.report(
                            //                     logic.comments![index], reason),
                            //             onLike: (int like) =>
                            //                 logic.changeLike(like, index),
                            //             onDelete: () => logic.delete(
                            //                 logic.comments![index], index),
                            //           ),
                            //         );
                            //       }),
                            //   const FooterLocator.sliver(),
                            // ] else
                            //   SliverToBoxAdapter(
                            //     child: Container(
                            //         color: Colours.white,
                            //         padding: EdgeInsets.only(bottom: 16),
                            //         child: const NoDataWidget(
                            //             tip: '还没有评论哦', height: 250)),
                            //   ),
                            // SliverToBoxAdapter(child: Container(height: 50))
                          ],
                        ),
                      ),
                    ),
                  ),
                  //input()
                ],
              ),
            ),
          );
        });
  }

  Widget appBarTitle() {
    return AnimatedCrossFade(
      firstCurve: Curves.easeIn,
      secondCurve: Curves.easeOut,
      layoutBuilder: (topChild, topChildKey, bottomChild, bottomChildKey) {
        return Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Positioned(
              key: bottomChildKey,
              child: bottomChild,
            ),
            Positioned(
              key: topChildKey,
              child: topChild,
            ),
          ],
        );
      },
      firstChild: Styles.userAppbarTitle(
          logo: logic.data?.logo,
          name: logic.data?.publisherName,
          focus: logic.data?.focus,
          userId: logic.data?.publisherId,
          onTap: (value) => logic.getNews()),
      secondChild: const QsText('内容详情'),
      crossFadeState:
          logic.showTop ? CrossFadeState.showFirst : CrossFadeState.showSecond,
      duration: const Duration(milliseconds: 300),
    );
  }

  Widget input() {
    return CommentInput(
      onSend: logic.sendChat,
      append: [
        AssetItem(
          onTap: () => logic.onZan(),
          direction: AssetDirection.ltr,
          asset: logic.data?.isLike == 1 ? 'zan_red.png' : 'zan.png',
          name: (logic.data?.likeNum.hasValue ?? false)
              ? '${logic.data?.likeNum}'
              : '赞',
          assetSize: 24,
          space: 4,
          textStyle: const TextStyle(fontSize: 14, color: Colours.text),
        ),
        Container(width: 22),
        AssetItem(
          onTap: logic.toComment,
          direction: AssetDirection.ltr,
          asset: "comment.png",
          name: (logic.data?.commentNum.hasValue ?? false)
              ? '${logic.data?.commentNum}'
              : '评',
          assetSize: 24,
          space: 4,
          textStyle: const TextStyle(fontSize: 14, color: Colours.text),
        ),
        Container(width: 22),
        GestureDetector(
          onTap: logic.onCollect,
          child: Image.asset(
              Utils.getImgPath(logic.data?.collectId == 0
                  ? "collection.png"
                  : "collection_red.png"),
              width: 24,
              height: 24),
        ),
      ],
    );
  }
}
